package com.zxg.zbc.biz.manager.impl;

import java.io.InputStream;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.zxg.zbc.biz.manager.PathManager;

public class PathManagerImpl implements PathManager {

  private String serverPath;

  private String endpoint   = "http://oss-cn-shanghai.aliyuncs.com";
  private String aliyunPath = "http://img2.zhixiangge.com/";
  private String key        = "";
  private String sec        = "";

  @Override
  public String getUploadFilePath() {
    return this.getServerPath();
  }

  public String getServerPath() {
    return serverPath;
  }
  public String getServerPath(String bucket) {
    if (bucket.equalsIgnoreCase("zxg"))
      return " http://img.zhixiangge.com/";
    return serverPath;
  }
  public void setServerPath(String serverPath) {
    this.serverPath = serverPath;
  }

  @Override
  public String uploadToAliyun(InputStream input, Long userId, String fileExtName) {

    String objectkey = generateKey(userId, fileExtName);
    // accessKey请登录https://ak-console.aliyun.com/#/查看
    String accessKeyId = key;
    String accessKeySecret = sec;
    // 创建OSSClient实例
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    // 上传文件流
    PutObjectResult res = ossClient.putObject("zxg-media", objectkey, input);

    // 关闭client
    ossClient.shutdown();
    if (res != null) {
      return objectkey;
    }
    return null;
  }

  private String generateKey(Long userId, String fileExtName) {
    return "hbg" + "_" + userId + "_" + System.currentTimeMillis() + "_hbg." + fileExtName;
  }

  public String getEndpoint() {
    return endpoint;
  }

  public void setEndpoint(String endpoint) {
    this.endpoint = endpoint;
  }

  public String getAliyunPath() {
    return aliyunPath;
  }

  public void setAliyunPath(String aliyunPath) {
    this.aliyunPath = aliyunPath;
  }

  @Override
  public String uploadToAliyun(InputStream input, String objectkey, String bucket) {

    // accessKey请登录https://ak-console.aliyun.com/#/查看
    String accessKeyId = key;
    String accessKeySecret = sec;
    // 创建OSSClient实例
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    // 上传文件流
    PutObjectResult res = ossClient.putObject(bucket, objectkey, input);

    // 关闭client
    ossClient.shutdown();
    if (res != null) {
      return objectkey;
    }
    return null;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public void setSec(String sec) {
    this.sec = sec;
  }

}
